package cn.foolishbird.crow.captcha;

import cn.foolishbird.crow.core.CrowEnum;

import java.util.Map;
import java.util.Objects;

/**
 * 验证码管理器
 *
 * @author foolish-bird
 */
public final class CaptchaManager {

    private final Map<Enum<? extends CrowEnum>, CaptchaStrategy<?>> captchaStrategyMap;

    public CaptchaManager(Map<Enum<? extends CrowEnum>, CaptchaStrategy<?>> captchaStrategyMap) {
        this.captchaStrategyMap = captchaStrategyMap;
    }

    /**
     * 根据验证码id创建验证码
     *
     * @return
     */
    public final <I> Captcha<I> createCaptcha(Enum<? extends CrowEnum> type) {
        if (Objects.isNull(captchaStrategyMap) || captchaStrategyMap.isEmpty()) {
            throw new RuntimeException("验证码策略实现不能为空");
        }

        CaptchaStrategy strategy = captchaStrategyMap.get(type);
        if (Objects.isNull(strategy)) {
            throw new RuntimeException("不支持该类型验证码策略");
        }
        return strategy.createCaptcha();
    }

    /**
     * 校验是否是有效验证码
     *
     * @param captcha 验证码内容
     * @return
     */
    public final <V> boolean verifyCaptcha(Enum<? extends CrowEnum> type, Captcha<V> captcha) {
        if (Objects.isNull(captchaStrategyMap) || captchaStrategyMap.isEmpty()) {
            throw new RuntimeException("验证码策略实现不能为空");
        }

        CaptchaStrategy strategy = captchaStrategyMap.get(type);
        if (Objects.isNull(strategy)) {
            throw new RuntimeException("不支持该类型验证码策略");
        }
        return strategy.verifyCaptcha(captcha);
    }

}
